--
-- Author: shunguo.chen
-- Date: 2017-11-27 12:07:08
--
-- MountPanel

local AvatarFactory = app:getClass("AvatarFactory")
local ScrollViewExtend = require("app.widget.ScrollViewExtend")
local ListViewVertical = require("app.widget.listview.ListViewVertical")
local MountRender = import(".renders.MountRender")

local ClassRef = app.mvc.createPanelClass(...)

local MOUNT_GET_STR = L("lua_code_text_508")
local MOUNT_UP_STR = L("lua_code_text_192")
local MOUNT_DOWN_STR = L("lua_code_text_403")
local MOUNT_NUM_STR = L("lua_code_text_6")
local MOUNT_MAX_STR = L("lua_code_text_60")
local MOUNT_NO_CELECT_STR = L("lua_code_text_420")

function ClassRef.create(node)
    local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.MountPanel))
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init()
    return sprite
end


function ClassRef:init(data)
    self.super.init(self, data)

    -- left
    -- ScrollView
    local params = {
        renderClass = MountRender,
        perNum = 3,
        gapY = 6,
        paddingLeft = 2,
        paddingRight = 6,
        isMultipleLayer = true,
        cellEventProxy = function(eventName, render)
            if render then
                self:setCurRender(render)
            end
		end,
    }
    self._sv = ListViewVertical.new(self._ui["Panel/ScrollView"], params)
    self._sv:setCellsShareData({listviewType = Enums.MountListViewType.MountPanelType})
    -- speed
    self._ui["Panel/Panel_left/Button1"]:addClickEventListener(function()
            executeFunc(self._onOperate, "openSpeed")
        end)
    
    self._ui["Panel/Panel_left/Button2"]:addClickEventListener(function()
        if not UIHandler:isFunctionOpen(Constant.FUNC_TYPE_CORE_PROP) then
            display.showFunctionNotOpenDetail(Constant.FUNC_TYPE_CORE_PROP)
            return false
        end
        executeFunc(self._onOperate, "openCorePropStar")
    end)

    
    -- mount
    local con = self._ui.Panel_mount
    self._nameText = con:getChildByName("name")
    self._descText = con:getChildByName("Text")
    self._mountCon = con:getChildByName("Node_position")

    self._tipText = con:getChildByName("Text_tip")
    self._barCon = con:getChildByName("bar")
    self._bar = con:findChild("bar/LoadingBar")
    self._barText = con:findChild("bar/num")

    self._playIndex = 1
    display.nodeTouchOneByOne(self._mountCon, function(posX,posY)
        if self:isVisible() then
            local armature = self._mountCon:getChildByTag(0)
            if armature and armature:containWorldPoint(posX, posY) then
                self:_playAnimation(armature, true)
            end
        end
        return false
    end)

    self._tickPanel = con:findChild("Panel_tick")
    self._tickBtn = con:findChild("Panel_tick/Button")
    self._tickBtn:addClickEventListener(function(sender)
            local isBright = sender:isBright()
            sender:setBright(not isBright)
            self:_refreshAvatar()
        end)

    self._btnDot = con:findChild("dot")
    self._equipBtn = con:findChild("Button")
    self._unloadBtn = con:findChild("Button_unload")
    self._btnText = self._equipBtn:getChildByName("name")
    self._equipBtn:addClickEventListener(function()
        if not self._curSelectRenderData then
            return
        end
        local mount = self._curSelectRenderData
        local str = self._btnText:getString()

        if str == MOUNT_UP_STR then
            executeFunc(self._onOperate, "equipMount", mount)
            self._unloadBtn:setVisible(true)
            self._equipBtn:setVisible(false)
        else
            executeFunc(self._onOperate, "openGet", mount)
        end
    end)

    self._unloadBtn:addClickEventListener(function()
        if not self._curSelectRenderData then
            return
        end
        local mount = self._curSelectRenderData
        executeFunc(self._onOperate, "unequipMount", mount)
        self._unloadBtn:setVisible(false)
        self._equipBtn:setVisible(true)
    end)

    self._timeChampion = con:getChildByName("time_champion")
    self._timeChampionBg = con:findChild("time_champion/bg")
    self._timeText = con:findChild("time_champion/text")
    self._timeTipText = con:getChildByName("tip")

    self:refreshMountCorePorp()
end

-- 119，点击骑乘按钮
-- 120，查看收集加速属性
function ClassRef:getGuideNode(id)
    if id == 119 then
        return self._equipBtn
    elseif id == 120 then
        return self._ui["Panel/Panel_left/bg"]
    end
end

function ClassRef:onOperate(cb)
    self._onOperate = cb
end

function ClassRef:getScrollView()
    return self._sv
end

local MountAnimations = {"ride_idle","ride_move"}
function ClassRef:_playAnimation(armature, isNext)
    isNext = isNext or false
    if isNext then
        self._playIndex = self._playIndex + 1
        if self._playIndex > #MountAnimations then
            self._playIndex = 1
        end
    end
    armature:play(MountAnimations[self._playIndex])
end

function ClassRef:_refreshAvatar()
    self._mountCon:removeAllChildren()

    -- 1. 玩家当前坐骑，骑上
    -- 2. 非当前坐骑，按tickBtn显示

    local tid = self._mount.tid
    local size = self._mount:getSize()
    local armature
    if self._mount:isRiding() then
        self._tickPanel:setVisible(false)
        local params = UD:getAvatarParams()
        params.mountID = tid
        armature = AvatarFactory.createHero(params, false)
    else
        if self._mount:canShowPassenger() then
            self._tickPanel:setVisible(true)
        else
            self._tickPanel:setVisible(false)
        end
        if self._tickBtn:isBright() then
            -- 不显示玩家
            armature = AvatarFactory.createRideById(tid, false)
        else
            local params = UD:getAvatarParams()
            params.mountID = tid
            armature = AvatarFactory.createHero(params, false)
        end
    end

    if armature then
        armature:setScale(size)
        self._mountCon:addChild(armature)
        armature:setTag(0)
        self:_playAnimation(armature)

        local box = armature:getBoundingBox()
        local pos = self._mountCon:convertToNodeSpace(cc.p(box.x + box.width/2, box.y))
        armature:setPositionX(-pos.x)
    end
end

function ClassRef:selectRender(uid)
    if self._curSelectRenderData and uid ~= self._curSelectRenderData.uid then
        self:setRenderSelected(self._curSelectRenderData.uid, false)
    end
    self:setRenderSelected(uid, true)
end

function ClassRef:setRenderSelected(uid, b)
    self._sv:foreachCellModels(function(cellModel, data)
        if data.uid == uid then
            if cellModel.cell then
                cellModel.cell:setSelected(b)
            else
                cellModel:setSelected(b)
            end
            if b then
                self._curSelectRenderData = data
            end
            return true
        end
    end)
end

function ClassRef:clearSelect()
    if self._curSelectRenderData then
        self._sv:foreachCellModels(function(cellModel, data)
            if data.uid == self._curSelectRenderData.uid then
                if cellModel.cell then
                    cellModel.cell:setSelected(false)
                else
                    cellModel:setSelected(false)
                end
                return true
            end
        end)
        self._curSelectRenderData = nil
    end
end

function ClassRef:clearRiding()
    self._sv:foreachVisibleCells(function(cell)
        cell:setRiding(false)
    end)
end

function ClassRef:refreshCurRender()
    if self._curSelectRenderData then
        self._sv:foreachVisibleCellModels(function(cellModel, data)
            if cellModel.cell and data.uid == self._curSelectRenderData.uid then
                cellModel.cell:refresh()
                return true
            end
        end)
    end
end

function ClassRef:setCurRender(render)
    local data = render:getData()
    self:setCurRenderData(data)
end

function ClassRef:setCurRenderData(data)
    if not data then return end

    if self._curSelectRenderData and data.uid ~= self._curSelectRenderData.uid then
        self:setRenderSelected(self._curSelectRenderData.uid, false)
        self:setRenderSelected(data.uid, true)
    else
        self:setRenderSelected(data.uid, true)
    end
    self:refreshMount(data)
end

function ClassRef:getMount()
    return self._mount
end

function ClassRef:refreshMount(mount)
    mount = mount or self._mount
    self._mount = mount

    local name = mount:getName()
    if not mount:haveMount() then
        name = name .. " (" .. L("text_11800011") .. ")"
    end
    self._nameText:setString(name)
    self._descText:setString(mount:getDesc())

    self:refreshMountCollect()

    local str
    local hasRedPoint = false
    if mount:haveMount() then
        -- str = mount:isRiding() and MOUNT_DOWN_STR or MOUNT_UP_STR
        str = MOUNT_UP_STR
    else
        str = MOUNT_GET_STR
        hasRedPoint = mount:checkComposition()
    end
    self._btnText:setString(str)
    self._btnDot:setVisible(hasRedPoint)

    self._equipBtn:setVisible(not mount:isRiding())
    self._unloadBtn:setVisible(mount:isRiding())

    self:_refreshAvatar()

    self:refreshMountTimeChampion()
    self:refreshMountCorePorp()
 
end

function ClassRef:refreshMountCorePorp()
    if not UIHandler:isFunctionOpen(Constant.FUNC_TYPE_CORE_PROP) then
        self._ui["Panel/Panel_left/img_lock"]:setVisible(true)
    else
        self._ui["Panel/Panel_left/img_lock"]:setVisible(false)
    end
end

function ClassRef:refreshMountCollect()
    local mount = self._mount

    local tipStr
    if mount:canBeComposed() then
        if mount:isMaxQuality() and mount:haveMount() then
            tipStr = MOUNT_MAX_STR
        else
            local haveNum, needNum = mount:getQualityCostNum()
            self._bar:setPercent(haveNum/needNum * 100)
            self._barText:setString(haveNum .. "/" .. needNum)
        end
    else
        if mount:haveMount() then
            tipStr = MOUNT_MAX_STR
        else
            -- tipStr = MOUNT_NO_CELECT_STR
            tipStr = ""
        end
    end
    local isPoundFlag = mount:isPoundEnable()
    self._tipText:setVisible(tipStr ~= nil and isPoundFlag)
    self._barCon:setVisible(tipStr == nil and isPoundFlag)

    if tipStr then
        self._tipText:setString(tipStr)
    end
end

function ClassRef:refreshMountTimeChampion()
    local mount = self._mount
    if mount:getDuration() ~= 0 then --有时限的坐骑显示倒计时
        self._timeChampion:setVisible(true)
        self:setTimeStr(mount:getDuration())
        --根据文本长度调整背景长度
        local width = self._timeText:getVirtualRendererSize().width
        local oldW,oldH = self._timeChampion:getContentSize2()
        self._timeChampionBg:setContentSize(cc.size(width+10, oldH))

        --根据坐骑名字长度动态调整限时位置
        local mountNameWidth = self._nameText:getVirtualRendererSize().width
        self._timeChampion:setPositionX(30 + mountNameWidth)
    else
        self._timeChampion:setVisible(false)
    end

    if mount:isPoundEnable() then --是否可以放入兽栏
        self._timeTipText:setVisible(false)
    else
        self._timeTipText:setVisible(true)
    end
end

function ClassRef:setTimeStr(time)
    if 0 >= time then
        return
    end
    local str = ""
    local serverTime = app.session:getServerTime() or os.time()
	if serverTime < time then
		local params = TimeUtil.secondsToStr((time - serverTime), 4)
        if not params then
            str = L("countdowen_max")
        else
            if params[1] then
                str = str..string.format(L("countdowen_day"), params[1])
            end
            if params[2] then
                str = str..string.format(L("countdowen_hour"), params[2])
            end
            if params[3] then
                str = str..string.format(L("countdowen_min"), params[3])
            end
        end
        self._timeText:setString(str)
	end
end

function ClassRef:setMountNum(cur, max)
    self._ui["Panel/Panel_left/mount_num"]:setString(string.format(MOUNT_NUM_STR, cur, max))
end

function ClassRef:setTotalStar(num)
    self._ui["Panel/Panel_left/star_num"]:setString(string.format(L("MountTotalStar"), num))
end


function ClassRef:setMountSpeed(speed)
    -- self._ui["Panel/Panel_left/mount_num"]:setString(string.format("+%s%%", speed))
end

function ClassRef:reloadData(data, isTop)
    if isTop then
        self._sv:reloadData(data, {startIndex = 1})
    else
        self._sv:reloadData(data)
    end
end

function ClassRef:refreshScrollView()
    self._sv:refreshVisibleCells()
end

function ClassRef:setSelectedByIndex(index)
    local data = self._sv:getDataByIndex(index)
    if data then
        self:setCurRenderData(data)
    end
end

return ClassRef
